const axios = require('axios');

const BASE_URL = 'http://localhost:3001';
let adminToken = '';

// 测试数据
const testData = {
  adminCredentials: {
    adminname: 'admin',
    password: '123456'
  }
};

// 辅助函数：发送HTTP请求
async function makeRequest(method, url, data = null, headers = {}) {
  try {
    const config = {
      method,
      url: `${BASE_URL}${url}`,
      headers: {
        'Content-Type': 'application/json',
        ...headers
      }
    };
    
    if (data) {
      config.data = data;
    }
    
    const response = await axios(config);
    return {
      success: true,
      status: response.status,
      data: response.data
    };
  } catch (error) {
    return {
      success: false,
      status: error.response?.status || 0,
      data: error.response?.data || { message: error.message }
    };
  }
}

// 管理员登录
async function adminLogin() {
  console.log('\n=== 管理员登录测试 ===');
  const result = await makeRequest('POST', '/admin/admin/login', testData.adminCredentials);
  
  if (result.success && result.data.code === '200' && result.data.data && result.data.data.token) {
    adminToken = result.data.data.token;
    console.log('✓ 管理员登录成功');
    console.log(`Token: ${adminToken.substring(0, 20)}...`);
    return true;
  } else {
    console.log('✗ 管理员登录失败:', result.data.message || '未知错误');
    console.log('完整响应:', JSON.stringify(result.data, null, 2));
    return false;
  }
}

// 测试1: 获取评价列表
async function testGetReviewList() {
  console.log('\n=== 测试1: 获取评价列表 ===');
  
  // 测试无token访问
  console.log('1.1 测试无token访问...');
  const noTokenResult = await makeRequest('GET', '/admin/review/list');
  console.log(`状态码: ${noTokenResult.status}`);
  console.log(`响应: ${JSON.stringify(noTokenResult.data)}`);
  
  // 测试有效token访问
  console.log('\n1.2 测试有效token访问...');
  const validResult = await makeRequest('GET', '/admin/review/list', null, {
    'token': adminToken
  });
  console.log(`状态码: ${validResult.status}`);
  console.log(`响应: ${JSON.stringify(validResult.data)}`);
  
  // 测试分页参数
  console.log('\n1.3 测试分页参数...');
  const pageResult = await makeRequest('GET', '/admin/review/list?page=1&limit=5', null, {
    'token': adminToken
  });
  console.log(`状态码: ${pageResult.status}`);
  console.log(`响应: ${JSON.stringify(pageResult.data)}`);
}

// 测试2: 获取评价统计
async function testGetReviewStatistics() {
  console.log('\n=== 测试2: 获取评价统计 ===');
  
  // 测试无token访问
  console.log('2.1 测试无token访问...');
  const noTokenResult = await makeRequest('GET', '/admin/review/statistics');
  console.log(`状态码: ${noTokenResult.status}`);
  console.log(`响应: ${JSON.stringify(noTokenResult.data)}`);
  
  // 测试有效token访问
  console.log('\n2.2 测试有效token访问...');
  const validResult = await makeRequest('GET', '/admin/review/statistics', null, {
    'token': adminToken
  });
  console.log(`状态码: ${validResult.status}`);
  console.log(`响应: ${JSON.stringify(validResult.data)}`);
}

// 测试3: 获取评价详情
async function testGetReviewDetail() {
  console.log('\n=== 测试3: 获取评价详情 ===');
  
  // 先获取一个评价ID用于测试
  const listResult = await makeRequest('GET', '/admin/review/list?limit=1', null, {
    'token': adminToken
  });
  
  let reviewId = null;
  if (listResult.data && listResult.data.data && listResult.data.data.list && listResult.data.data.list.length > 0) {
    reviewId = listResult.data.data.list[0]._doc?.reviewid || listResult.data.data.list[0].reviewid;
  }
  
  if (reviewId) {
    console.log(`3.1 测试获取评价详情 (ID: ${reviewId})...`);
    const detailResult = await makeRequest('GET', `/admin/review/detail/${reviewId}`, null, {
      'token': adminToken
    });
    console.log(`状态码: ${detailResult.status}`);
    console.log(`响应: ${JSON.stringify(detailResult.data)}`);
  } else {
    console.log('3.1 跳过详情测试 - 没有可用的评价数据');
  }
  
  // 测试无效ID
  console.log('\n3.2 测试无效评价ID...');
  const invalidResult = await makeRequest('GET', '/admin/review/detail/99999', null, {
    'token': adminToken
  });
  console.log(`状态码: ${invalidResult.status}`);
  console.log(`响应: ${JSON.stringify(invalidResult.data)}`);
  
  // 测试无token访问
  console.log('\n3.3 测试无token访问...');
  const noTokenResult = await makeRequest('GET', '/admin/review/detail/1');
  console.log(`状态码: ${noTokenResult.status}`);
  console.log(`响应: ${JSON.stringify(noTokenResult.data)}`);
}

// 测试4: 删除评价
async function testDeleteReview() {
  console.log('\n=== 测试4: 删除评价 ===');
  
  // 先获取一个评价ID用于测试删除
  const listResult = await makeRequest('GET', '/admin/review/list?limit=1', null, {
    'token': adminToken
  });
  
  if (listResult.data && listResult.data.data && listResult.data.data.list && listResult.data.data.list.length > 0) {
    const reviewId = listResult.data.data.list[0]._doc?.reviewid || listResult.data.data.list[0].reviewid;
    console.log(`4.1 测试删除评价 (ID: ${reviewId})...`);
    const deleteResult = await makeRequest('DELETE', '/admin/review/delete', {
      reviewid: reviewId
    }, {
      'token': adminToken,
      'Content-Type': 'application/json'
    });
    console.log(`状态码: ${deleteResult.status}`);
    console.log(`响应: ${JSON.stringify(deleteResult.data)}`);
  } else {
    console.log('4.1 跳过删除测试 - 没有可用的评价数据');
  }
  
  // 测试无效ID删除
  console.log('\n4.2 测试删除无效评价ID...');
  const invalidResult = await makeRequest('DELETE', '/admin/review/delete', {
    reviewid: 99999
  }, {
    'token': adminToken
  });
  console.log(`状态码: ${invalidResult.status}`);
  console.log(`响应: ${JSON.stringify(invalidResult.data)}`);
  
  // 测试缺少reviewid参数
   console.log('\n4.3 测试缺少reviewid参数...');
   const missingParamResult = await makeRequest('DELETE', '/admin/review/delete', {}, {
     'token': adminToken,
     'Content-Type': 'application/json'
   });
   console.log(`状态码: ${missingParamResult.status}`);
   console.log(`响应: ${JSON.stringify(missingParamResult.data)}`);
  
  // 测试无token访问
  console.log('\n4.4 测试无token访问...');
  const noTokenResult = await makeRequest('DELETE', '/admin/review/delete', {
    reviewid: 1
  });
  console.log(`状态码: ${noTokenResult.status}`);
  console.log(`响应: ${JSON.stringify(noTokenResult.data)}`);
}

// 主测试函数
async function runAdminReviewTests() {
  console.log('开始管理员评价接口测试...');
  console.log('服务器地址:', BASE_URL);
  
  try {
    // 管理员登录
    const loginSuccess = await adminLogin();
    if (!loginSuccess) {
      console.log('\n❌ 管理员登录失败，无法继续测试');
      return;
    }
    
    // 执行所有测试
    await testGetReviewList();
    await testGetReviewStatistics();
    await testGetReviewDetail();
    await testDeleteReview();
    
    console.log('\n=== 测试完成 ===');
    console.log('✓ 所有管理员评价接口测试已执行完毕');
    
  } catch (error) {
    console.error('\n❌ 测试过程中发生错误:', error.message);
  }
}

// 运行测试
if (require.main === module) {
  runAdminReviewTests().then(() => {
    process.exit(0);
  }).catch(error => {
    console.error('测试失败:', error);
    process.exit(1);
  });
}

module.exports = {
  runAdminReviewTests,
  testGetReviewList,
  testGetReviewStatistics,
  testGetReviewDetail,
  testDeleteReview
};